import React, { useState, useEffect, useCallback, useRef } from 'react';
import axios from 'axios';
import { io, Socket } from 'socket.io-client';
import { useNavigate, useSearchParams } from 'react-router-dom';

import { API_BASE_URL_MESSAGE, WS_BASE_URL } from '../utils/config';

import Dhat from './Dhat';
import Header from './components/chat/Header';
import Nav from './components/chat/nav';
import List from './components/chat/List';
import CreateGroupModal from './components/chat/CreateGroupModal';
import GroupChat from './components/chat/GroupChat';

import './Chat.css';

interface HomeProps {
  currentUser: {
    _id?: string;
    username: string;
    image: string;
    isLoggedIn: boolean;
  };
}

const Home: React.FC<HomeProps> = ({ currentUser }) => {
  // 接口定义移到组件内部，遵循项目规�?
  interface User {
    _id: string;
    username: string;
    image: string;
    isLoggedIn?: boolean;
  }

  interface Group {
    _id: string;
    name: string;
    members: User[];
    createdBy: User;
    createdAt: string;
  }

  // 统一的聊天项接口
  interface ChatItem {
    _id: string;
    username: string;
    name: string;
    image: string;
    type: 'user' | 'group';
    isTop: boolean;
    data?: User | Group;
  }

  // 更新群聊名称的函数
  const updateGroupName = (groupId: string, newName: string) => {
    setGroups(prevGroups =>
      prevGroups.map(group =>
        group._id === groupId ? { ...group, name: newName } : group
      )
    );
  };

  interface Message {
    _id: string;
    from: string;
    to: string;
    message: string;
    messageType: string;
    timestamp: Date;
  }

  interface LastMessage {
    [username: string]: {
      message: string;
      messageType: string;
      timestamp: Date;
    };
  }

  const [users, setUsers] = useState<User[]>([]);
  const [groups, setGroups] = useState<Group[]>([]);
  const [currentUserId, setCurrentUserId] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [selectedGroup, setSelectedGroup] = useState<Group | null>(null);
  const [, setSocket] = useState<Socket | null>(null);
  const [lastMessages, setLastMessages] = useState<LastMessage>({});
  const [lastMessagesLoading, setLastMessagesLoading] = useState(false);
  const [showCreateGroupModal, setShowCreateGroupModal] = useState(false);
  const [chatListUpdateTrigger, setChatListUpdateTrigger] = useState(0);
  const [refreshTrigger, setRefreshTrigger] = useState(0); // 用于触发重新排序

  // 使用路由导航
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  // localStorage存储策略
  const getPinChatStatus = (username: string): boolean => {
    const status = localStorage.getItem(`pinChat_${username}`);
    return status === 'true';
  };

  const setPinChatStatus = (username: string, isPinned: boolean) => {
    localStorage.setItem(`pinChat_${username}`, isPinned.toString());
    // 设置更新标志，通知其他页面状态已变化
    localStorage.setItem('pinChat_updated', Date.now().toString());
  };

  // 群聊置顶状态管理
  const getPinGroupStatus = (groupName: string): boolean => {
    const status = localStorage.getItem(`pinGroup_${groupName}`);
    return status === 'true';
  };

  const setPinGroupStatus = (groupName: string, isPinned: boolean) => {
    localStorage.setItem(`pinGroup_${groupName}`, isPinned.toString());
    // 设置更新标志，通知其他页面状态已变化
    localStorage.setItem('pinGroup_updated', Date.now().toString());
  };

  // 事件监听机制 - 监听localStorage变化
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === 'pinChat_updated' || e.key === 'pinGroup_updated') {
        // 触发重新排序
        setRefreshTrigger(prev => prev + 1);
      }
    };

    window.addEventListener('storage', handleStorageChange);

    // 组件内部状态变化也需要触发更新
    const handleInternalUpdate = () => {
      setRefreshTrigger(prev => prev + 1);
    };

    // 监听自定义事件
    window.addEventListener('pinChatUpdated', handleInternalUpdate);
    window.addEventListener('pinGroupUpdated', handleInternalUpdate);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('pinChatUpdated', handleInternalUpdate);
      window.removeEventListener('pinGroupUpdated', handleInternalUpdate);
    };
  }, []);

  // 获取每个用户的最后一条消息
  const fetchLastMessages = useCallback(
    async (userList: User[]) => {
      try {
        setLastMessagesLoading(true);
        const lastMessagesData: LastMessage = {};

        for (const user of userList) {
          try {
            const response = await axios.get(
              `${API_BASE_URL_MESSAGE}/chat/last-message?from=${currentUser?.username}&to=${user.username}`
            );
            if (response.data.code === 200 && response.data.data) {
              lastMessagesData[user.username] = response.data.data;
            }
          } catch (error) {
            console.error(`获取用户 ${user.username} 的最后消息失败:`, error);
          }
        }

        setLastMessages(lastMessagesData);
      } catch (error) {
        console.error('获取最后消息失败:', error);
      } finally {
        setLastMessagesLoading(false);
      }
    },
    [currentUser?.username]
  );

  // 初始化Socket连接
  useEffect(() => {
    let newSocket: Socket;

    const connectSocket = () => {
      try {
        newSocket = io(WS_BASE_URL, {
          transports: ['websocket', 'polling'],
          timeout: 20000,
          reconnection: true,
          reconnectionAttempts: 5,
          reconnectionDelay: 1000,
        });

        newSocket.on('connect', () => {
          console.warn('Socket连接成功');
          setSocket(newSocket);
        });

        newSocket.on('disconnect', () => {
          console.warn('Socket连接断开');
          setSocket(null);
        });

        // 监听群名称修改事件
        newSocket.on(
          'group_name_changed',
          (data: {
            groupId: string;
            newName: string;
            oldName: string;
            changedBy: string;
          }) => {
            console.warn('收到群名称修改通知:', data);
            updateGroupName(data.groupId, data.newName);
          }
        );

        // 连接错误
        newSocket.on('connect_error', (error: unknown) => {
          console.error('Home Socket连接失败:', error);
        });
      } catch (error) {
        console.error('Socket连接初始化失败:', error);
      }
    };

    connectSocket();

    return () => {
      if (newSocket) {
        newSocket.disconnect();
      }
    };
  }, []);

  // 获取用户列表
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await axios.get(
          `${API_BASE_URL_MESSAGE}/users?currentUser=${currentUser?.username}`
        );
        if (response.data.code === 200) {
          setUsers(response.data.data);
          fetchLastMessages(response.data.data);
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        setError('获取用户列表失败');
      } finally {
        setLoading(false);
      }
    };

    fetchUsers();
  }, [currentUser?.username, fetchLastMessages]);

  // 获取当前用户ID
  useEffect(() => {
    const fetchCurrentUserId = async () => {
      if (!currentUser?.username) return;

      try {
        console.warn(
          '使用临时解决方案，当前用户名作为用户ID:',
          currentUser?.username
        );
        setCurrentUserId(currentUser.username);
      } catch (error) {
        console.error('获取当前用户信息失败:', error);
      }
    };

    fetchCurrentUserId();
  }, [currentUser?.username]);

  // 监听聊天列表更新
  useEffect(() => {
    const handleStorageChange = () => {
      const needsUpdate = localStorage.getItem('chatListNeedsUpdate');
      if (needsUpdate === 'true') {
        localStorage.removeItem('chatListNeedsUpdate');
        setChatListUpdateTrigger(prev => prev + 1);
      }
    };

    window.addEventListener('storage', handleStorageChange);

    // 检查是否需要立即更新
    const needsUpdate = localStorage.getItem('chatListNeedsUpdate');
    if (needsUpdate === 'true') {
      localStorage.removeItem('chatListNeedsUpdate');
      setChatListUpdateTrigger(prev => prev + 1);
    }

    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);

  // 获取用户所在的群聊列表
  useEffect(() => {
    const fetchGroups = async () => {
      if (!currentUserId) {
        console.warn('fetchGroups: currentUserId 为空，跳过群聊获取');
        return;
      }

      try {
        console.warn('开始获取群聊列表，当前用户ID:', currentUserId);
        const response = await axios.get(
          `${API_BASE_URL_MESSAGE}/groups?userId=${currentUserId}`
        );
        console.warn('群聊API响应:', {
          status: response.status,
          statusText: response.statusText,
          data: response.data,
          headers: response.headers,
        });

        if (response.status === 200) {
          console.warn('获取群聊列表成功，数据:', response.data);
          if (Array.isArray(response.data)) {
            console.warn('群聊数据是数组，长度:', response.data.length);
            setGroups(response.data);
          } else {
            console.warn(
              '群聊数据不是数组，类型:',
              typeof response.data,
              '数据:',
              response.data
            );
            if (
              response.data &&
              response.data.data &&
              Array.isArray(response.data.data)
            ) {
              console.warn(
                '从response.data.data中获取群聊数',
                response.data.data
              );
              setGroups(response.data.data);
            } else {
              console.warn('无法获取有效的群聊数');
              setGroups([]);
            }
          }
        } else {
          console.warn('群聊API返回200状态', response.status);
        }
      } catch (error) {
        console.error('获取群聊列表失败:', error);
        if (error && typeof error === 'object' && 'response' in error) {
          const axiosError = error as {
            response: { status: number; statusText: string; data: unknown };
          };
          console.error('错误响应详情:', {
            status: axiosError.response.status,
            statusText: axiosError.response.statusText,
            data: axiosError.response.data,
          });
        }
      }
    };

    fetchGroups();
  }, [currentUserId]);

  // 处理URL参数变化，设置selectedUser
  useEffect(() => {
    const chatParam = searchParams.get('chat');
    const userParam = searchParams.get('user');
    const groupParam = searchParams.get('groupId');

    if (chatParam === 'true' && userParam) {
      const user = users.find(u => u.username === userParam);
      if (user) {
        setSelectedUser(user);
        return;
      }
    }

    if (groupParam) {
      const group = groups.find(g => g._id === groupParam);
      if (group) {
        setSelectedGroup(group);
        return;
      }
    }

    // 如果没有匹配的参数，清除选择
    setSelectedUser(null);
    setSelectedGroup(null);
  }, [searchParams, users, groups]);

  // 处理用户点击
  const handleUserClick = (user: User) => {
    setSelectedUser(user);
    localStorage.setItem('selectedUser', JSON.stringify(user));
    navigate(`/?chat=true&user=${user.username}`);
  };

  // 处理群聊点击
  const handleGroupClick = (group: Group) => {
    setSelectedGroup(group);
    navigate(`/?chat=true&groupId=${group._id}`);
  };

  // 处理返回
  const handleBack = () => {
    setSelectedUser(null);
    setSelectedGroup(null);
    localStorage.removeItem('selectedUser');
    navigate('/');
  };

  // 处理标签点击
  const handleTabClick = (tab: string) => {
    setActiveTab(tab);
  };

  // 处理显示创建群聊弹窗
  const handleShowCreateGroup = () => {
    setShowCreateGroupModal(true);
  };

  // 处理群聊创建完成
  const handleGroupCreated = () => {
    setShowCreateGroupModal(false);
    // 重新获取群聊列表
    const fetchGroups = async () => {
      try {
        const response = await axios.get(
          `${API_BASE_URL_MESSAGE}/groups?userId=${currentUserId}`
        );
        if (response.status === 200 && Array.isArray(response.data)) {
          setGroups(response.data);
        }
      } catch (error) {
        console.error('重新获取群聊列表失败:', error);
      }
    };
    fetchGroups();
  };

  const formatTime = (date: Date | string) => {
    // 确保date是Date对象
    let dateObj: Date;
    if (typeof date === 'string') {
      dateObj = new Date(date);
    } else {
      dateObj = date;
    }

    // 检查日期是否有�?
    if (isNaN(dateObj.getTime())) {
      console.warn('无效的日期:', date);
      return '时间错误';
    }

    const now = new Date();
    const diff = now.getTime() - dateObj.getTime();
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    // 添加调试信息
    console.warn('时间格式', {
      original: date,
      parsed: dateObj,
      now: now,
      diff: diff,
      minutes: minutes,
      hours: hours,
      days: days,
    });

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    return dateObj.toLocaleDateString('zh-CN');
  };

  const getFilteredChatItems = (): ChatItem[] => {
    // 添加调试信息
    console.warn('getFilteredChatItems 调试信息:', {
      usersCount: users.length,
      groupsCount: groups.length,
      activeTab,
      currentUserId,
      refreshTrigger, // 添加刷新触发器信息
      users: users.map(u => ({ username: u.username, _id: u._id })),
      groups: groups.map(g => ({
        name: g.name,
        _id: g._id,
        membersCount: g.members.length,
      })),
    });

    const userItems: ChatItem[] = users.map(user => ({
      _id: user._id,
      username: user.username,
      name: user.username,
      image: user.image,
      type: 'user' as const,
      data: user,
      isTop: getPinChatStatus(user.username), // 获取置顶状态
    }));

    const groupItems: ChatItem[] = groups.map(group => ({
      _id: group._id,
      username: group.name,
      name: group.name,
      image: group.members[0]?.image || '',
      type: 'group' as const,
      data: group,
      isTop: getPinGroupStatus(group.name), // 使用群聊置顶状态
    }));

    const result = (() => {
      switch (activeTab) {
        case 'unread':
          return []; // 暂时没有未读消息逻辑
        case 'mention':
          return []; // 暂时没有@我逻辑
        case 'single':
          return userItems; // 单聊显示所有用�?
        case 'group':
          return groupItems; // 群聊显示所有群�?
        default:
          return [...userItems, ...groupItems]; // 全部显示用户和群�?
      }
    })();

    // 排序算法：置顶优先，然后按最后消息时间排序
    const sortedResult = result.sort((a, b) => {
      // 首先按置顶状态排序
      if (a.isTop && !b.isTop) return -1;
      if (!a.isTop && b.isTop) return 1;

      // 如果都是置顶或都不是置顶，按最后消息时间排序
      const aLastMessage = lastMessages[a.username];
      const bLastMessage = lastMessages[b.username];

      if (aLastMessage && bLastMessage) {
        return (
          new Date(bLastMessage.timestamp).getTime() -
          new Date(aLastMessage.timestamp).getTime()
        );
      }

      if (aLastMessage) return -1;
      if (bLastMessage) return 1;

      return 0;
    });

    console.warn('getFilteredChatItems 结果:', {
      resultCount: sortedResult.length,
      userItemsCount: userItems.length,
      groupItemsCount: groupItems.length,
      pinnedCount: sortedResult.filter(item => item.isTop).length,
      result: sortedResult.map(item => ({
        type: item.type,
        name: item.name,
        isTop: item.isTop,
      })),
    });

    return sortedResult;
  };

  const filteredChatItems = getFilteredChatItems();

  // 当置顶状态改变时，重新计算聊天列表
  useEffect(() => {
    // 这个useEffect会在chatListUpdateTrigger变化时触发
    // 从而重新渲染聊天列表
  }, [chatListUpdateTrigger]);

  // 如果选择了用户，显示聊天页面
  if (selectedUser) {
    return (
      <Dhat
        currentUser={currentUser}
        selectedUser={selectedUser}
        onBack={handleBack}
      />
    );
  }

  // 如果选择了群聊，显示群聊页面
  if (selectedGroup) {
    return (
      <GroupChat
        currentUser={currentUser}
        selectedGroup={selectedGroup}
        onBack={handleBack}
        onGroupNameUpdate={updateGroupName}
      />
    );
  }

  return (
    <div className="chat-container">
      {/* 头部 */}
      <Header
        currentUser={currentUser}
        onShowCreateGroup={handleShowCreateGroup}
      />

      {/* 导航标签 */}
      <Nav activeTab={activeTab} onTabClick={handleTabClick} />

      {/* 用户列表 */}
      <List
        loading={loading}
        error={error}
        filteredUsers={filteredChatItems}
        lastMessages={lastMessages}
        lastMessagesLoading={lastMessagesLoading}
        activeTab={activeTab}
        onUserClick={handleUserClick}
        onGroupClick={handleGroupClick}
        formatTime={formatTime}
      />

      {/* 群聊创建弹窗 */}
      <CreateGroupModal
        isVisible={showCreateGroupModal}
        onClose={() => setShowCreateGroupModal(false)}
        currentUser={currentUserId}
        onGroupCreated={handleGroupCreated}
      />
    </div>
  );
};

export default Home;
